package com.kapcb.mvc.advice;

import com.kapcb.common.constant.LogConstant;
import com.kapcb.common.result.ResultMessage;
import com.kapcb.context.core.ApplicationThreadContextHolder;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <a>Title: MvcResponseBodyAdvice </a>
 * <a>Author: kapcb <a>
 * <a>Description: MvcResponseBodyAdvice <a>
 *
 * @author Kpacb
 * @version 1.0
 * @date 2024/6/11 23:04
 * @since 1.0
 */
@RestControllerAdvice
public class MvcResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 是否开启拦截 true开启 false 不开启
     *
     * @param returnType    返回值类型
     * @param converterType 息转换器
     * @return 是否开启拦截
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 此处应该改为 true,否则除了异常外 走到此处为 false 后就直接返回,也不再继续往下走了！
        return true;
    }


    /**
     * 这里可以对body进行任何处理，比如添加公共字段、转换格式等
     *
     * @param body                  请求体
     * @param returnType            返回值类型
     * @param selectedContentType   使用的内容类型
     * @param selectedConverterType 使用的息转换器
     * @param request               请求
     * @param response              响应
     * @return 处理后的返回值
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultMessage) {
            ResultMessage<?> resultMessage = (ResultMessage<?>) body;
            resultMessage.setTraceId(ApplicationThreadContextHolder.get(LogConstant.LOG_TRACE_ID));
            return resultMessage;
        }
        return body;
    }

}
